package com.sfy.login.filter;

import com.alibaba.fastjson.JSON;

import com.sfy.login.anno.Token;
import com.sfy.login.common.RedisKey;
import com.sfy.login.entity.User;
import com.sfy.login.third.JedisUtil;
import com.sfy.login.vo.R;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description
 * @Author 谷晓天
 * @Date 2021/7/13 4:18 下午
 */

@Component //IOC
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、类型校验
        if (handler instanceof HandlerMethod) {
            //2、获取自定义注解
            Token token = ((HandlerMethod) handler).getMethodAnnotation(Token.class);
            if (token != null) {
                //需要传递令牌
                //4、获取请求传递的令牌
                String userToken = request.getHeader(RedisKey.USER_TOKEN);
                //5、校验令牌是否为空
                if (StringUtils.hasLength(userToken)) {
                    //验证令牌有效性 Redis
                    String key = RedisKey.USER_TOKEN + userToken;
                    if (JedisUtil.checkKey(key)) {
                        //当前请求合法  刷新有效期
                        JedisUtil.expire(key,RedisKey.USER_TOKEN_TIME);
                        User user = JSON.parseObject(JedisUtil.getStr(key), User.class);
                        JedisUtil.expire(RedisKey.USER_TOKEN_ID + user.getId(),RedisKey.USER_TOKEN_TIME);
                        //放行
                        return true;
                    }
                }else {
                    response.setContentType("application/json;Charset=UTF-8");
                    response.getWriter().write(JSON.toJSONString(R.fail("令牌无效")));
                    return false;
                }
            }else {
                return true;
            }
        }
        return true;
    }
}
